import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
import { CheckBox, DropDownBox, Form, NumberBox, SelectBox, TextBox, } from 'devextreme-react';
import Popup from 'devextreme-react/popup';
import React, { useCallback, useEffect, useImperativeHandle, useRef } from 'react';
import { useState } from 'react';
import { intl } from '@/utils';
import { useModel } from 'umi';
import { SimpleItem } from 'devextreme-react/form';
import { CpasIcon } from '~/public/cpas-ui';
import ReportPopup from "~/public/cpas-business/components-bs/ReportPopup";
import SubjectPopups from "~/public/cpas-business/components-bs/SubjectPopup";
import notify from 'devextreme/ui/notify';
// import PopupComponents from '../../../../../components/PopupComponents';
import { getSubjectInfo } from './service';
// import PTextBox from '';
import "./index.less"
import PTextBox from '@/pages/components/PTextBox';
import PopupComponents from '@/pages/components/PopupComponents';

const SubjectPopupData = React.forwardRef((props: any, ref: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;
    const { AccountDataID } = props

    const diaParams = useRef<AudDialogShowParams & any>();
    const SubjectRef = useRef<any>();
    const statementProjectRef = useRef<any>();
    const PopupComponentsRef = useRef<any>();
    const PTextBoxValue = useRef<any>();


    const [visible, setVisible] = useState<boolean>(false);
    const [selectedYears, setSelectedYears] = useState<any>('');
    // const [SubjectNumber, setSubjectNumber] = useState<string>('');
    const [SelectType, setSelectType] = useState<string>('资产');
    // const [SelectTypeData, setSelectTypeData] = useState<string>('');
    const [SelectName, setSelectName] = useState<string>('');

    const [superiorProject, setSuperiorProject] = useState<string>('');
    const [KMBHAdd, setKMBHAdd] = useState<string>("");
    const [KMBH, setKMBH] = useState<string>("");
    const [KMBHValue, setKMBHValue] = useState<string>("");
    const [PKMBH, setPKMBH] = useState<string>("");
    const [Satatejc, setSatatejc] = useState<string | number>("");
    const [KMMC, setKMMC] = useState<string>("");
    const [PKMBHState, setPKMBHState] = useState<boolean>(false);
    const [checkBoxState, setCheckBoxState] = useState<boolean>(true);



    const initialization = () => {
        setVisible(false);
        setCheckBoxState(true);
        setKMBHAdd("");
        setKMBH("");
        setPKMBH("");
        setKMMC("");
        setSatatejc("");
        setSuperiorProject('');
        setSelectedYears('');
        // setSubjectNumber('');
        setKMBHValue("");
        setPKMBHState(false);
        PTextBoxValue.current = '';
    };

    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (params: AudDialogShowParams & any) => {
            diaParams.current = params;
            // debugger;

            setCheckBoxState(!params?.args.isEdit);
            setVisible(true);
            setSelectName(params.args.datatKMFX);
            setSelectType(params.args.dataKMLX);
            setKMBHAdd(params?.args.ParentLevelKmbh);
            setPKMBH(params?.args.PKMBH);
            setSuperiorProject(params?.args.ParentLevel);
            setKMBH(params?.args.KMBH);
            if (params?.args.isEdit) {
                setSelectedYears(params?.args.itemNames);
                PTextBoxValue.current = params?.args.KMMC;
                setKMMC(params?.args.KMMC);
            } else {
                PTextBoxValue.current = '';
                setSelectedYears('');
            }
            setKMMC("");
        },
        close: () => { setVisible(false) }
    }));


    const changeObjData = useCallback(() => {
        const SubjectNumber = PTextBoxValue.current;
        let tempObj = {};
        const reg = /^[\s\S]*.*[^\s][\s\S]*$/
        if (reg.test(SubjectNumber)) {
            if (diaParams.current?.args.isEdit) {
                tempObj = { SubjectNumber, SelectName, SelectType, selectedYears, KMBHAdd, checkBoxState }
            } else {
                tempObj = {
                    KMBHValue, PKMBHState, KMMC, Satatejc, PKMBH, KMBH, superiorProject, KMBHAdd, SubjectNumber, SelectName, SelectType, selectedYears, checkBoxState
                }
            }
            console.log(tempObj, 'SubjectNumber-----@@@');
        } else {
            notify('不可输入空白', 'warning', 2000);
        }
        return tempObj;
    }, [KMBHValue, PKMBHState, KMMC, Satatejc, PKMBH, KMBH, superiorProject, KMBHAdd, SelectName, SelectType, selectedYears, checkBoxState]);


    const methods = () => {
        const tempObjData: any = changeObjData();
        if (!tempObjData.KMBHAdd) return notify('请输入科目编号', 'warning', 2000);
        diaParams.current?.okCallback(tempObjData);
        initialization();
    };

    const subjectPrompt = () => {
        const tempObjData: any = changeObjData();
        if (!tempObjData.KMBHAdd) return notify('请输入科目编号', 'warning', 2000);
        PopupComponentsRef.current.show({
            title: "选择报表项目",
            content: "一级科目未设置对应报表项目，是否继续？",
            okCallback: () => {
                diaParams.current?.okCallback(tempObjData);
                initialization();
            },
        });
    };

    const repeatMethod = async () => {
        const SubjectNumber = PTextBoxValue.current;
        let tempKMMCName = '';
        // 拼接科目编号
        if (!diaParams.current?.args.isEdit) {
            const r = await getSubjectInfo({
                dbname: dbname,
                Data_ID: AccountDataID,
                YSKMBH: `${KMBHAdd}`,
            })
            if (r.data.length > 0) return notify("此科目编号已存在，请重新输入", "warning", 2000);
        }

        if (superiorProject) {
            if (KMMC) {
                tempKMMCName = KMMC + '-' + SubjectNumber;
            } else {
                tempKMMCName = diaParams.current?.args.resolvess + '-' + SubjectNumber;
            }
        } else {
            tempKMMCName = SubjectNumber;
        };
        const res = await getSubjectInfo({
            dbname: dbname,
            Data_ID: AccountDataID,
            // superiorProject ? 上级科目有拼接  : 直接负值value
            KMMC: tempKMMCName
        });
        // debugger;
        if (res.data.length) {
            const tempData = res.data.filter((item: any) => item.KMBH !== KMBH);
            // debugger;
            if (tempData.length) {
                return notify("此科目名称已存在，请重新输入", "warning", 2000);
            }
        };
        if (!selectedYears && !superiorProject) return subjectPrompt();
        return methods();
    }
    const onCancel = useCallback(() => {
        initialization();
    }, []);

    const onOk = () => {
        if (diaParams.current?.okCallback) {
            if (!PTextBoxValue.current) return notify('请输入科目名称', 'warning', 2000);
            if (!KMBHAdd) return notify('请输入科目编号', 'warning', 2000);
            if (!diaParams.current?.args.isEdit) {
                const PKMBH1 = PKMBH.replace(/~\|/g, '');
                const a1 = KMBHAdd ? `${KMBHAdd}`.substring(0, PKMBH1.length) : KMBH.substring(0, PKMBH1.length);
                if (superiorProject && PKMBH1 !== a1) return notify("输入科目编号不符合规则,应该以父级编号为前缀!", "error", 3000);
                const regex = /^[A-Za-z0-9.]*[0-9]$/;
                const result = regex.test(KMBHAdd);
                if (!result) return notify("科目编号只能包含字母、数字和小数点，并且最后一位必须是数字", "error", 3000);

            }
            repeatMethod();
        };
    };
    // 科目方向
    const onSelectionChangedDirection = (e: any) => {
        setSelectName(e.selectedItem.name);
    }
    // 科目类型
    const onSelectionChangedType = (e: any) => {
        setSelectType(e.selectedItem.type);
    }

    const items = [{
        id: '0',
        name: '借',
    },
    {
        id: '1',
        name: '贷',
    }]

    const changeCheck = useCallback((v: boolean) => {
        setCheckBoxState(v);
    }, [checkBoxState]);
    return (
        <>
            <Popup
                ref={ref}
                visible={visible}
                title={diaParams.current?.args?.title}
                width={630}
                height={470}
                wrapperAttr={{
                    class: "fix-popup-title-width"
                }}
                {...props}
                onHiding={() => onCancel()}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },
                ]}
                // dragOutsideBoundary={true}
                resizeEnabled={true}
            >
                <div style={{ width: "100%" }} className='subjectsFormBox'>
                    <Form
                        colCount={2}
                        // labelLocation={"left"}
                        // labelMode={"outside"}
                        focusStateEnabled={true}
                        showColonAfterLabel={true}
                        alignItemLabels={true}
                        className='SubjectsForm'
                        width="100%"
                    >
                        <SimpleItem colSpan={2} label={{ text: '上级科目' }} >
                            <TextBox readOnly={true} disabled={diaParams.current?.args.isEdit}
                                className="TextBox_Style" valueChangeEvent='keyup' value={superiorProject} />
                            <span style={{ position: 'absolute', right: '3px', top: "6px" }}>
                                <CpasIcon type="icon-xinzengkemu" onClick={() => {
                                    if (diaParams.current?.args.isEdit) return;
                                    SubjectRef.current.show({
                                        title: "选择科目",
                                        dbname: dbname,
                                        Data_ID: AccountDataID,
                                        isHasFZZ: false,
                                        editUser: username,
                                        // 选择 模式 0：单选 1：多选连机选择
                                        selectMode: '0',
                                        // 是否为辅助账 
                                        auxiliaryState: false,
                                        // 是否可以选择上级科目
                                        isSelectSuperior: true,
                                        okCallback: (r: any, v: any) => {
                                            // 科目审定明细 界面增加一级科目在业务组件 需做更改
                                            console.log(r, v, 'r-------sssssssss----------');
                                            setKMBHValue(v[0].YSKMBH);
                                            setKMBHAdd(v[0].YSKMBH)
                                            setPKMBHState(false);
                                            setKMBH(v[0].KMBH);
                                            // 获取选中的数据
                                            if (Object.prototype.toString.call(r) === '[object Object]') {
                                                setSuperiorProject(r.code + '-' + r.KMMC);
                                                console.log(r, '@@@');
                                                setPKMBH(r.KMBH);
                                                setKMMC(r.KMMC);
                                                setSatatejc(r.JC);
                                            }
                                        },
                                    });
                                }} />
                                <CpasIcon type="icon-close1" onClick={() => {
                                    if (diaParams.current?.args.isEdit) return;
                                    setSuperiorProject('');
                                    setPKMBH('');
                                    setSatatejc("");
                                    if (KMBHAdd) {
                                        const value2 = `${KMBHAdd}${"~|"}`
                                        setKMBH(value2);
                                    } else {
                                        setKMBH('');
                                    }
                                    setPKMBHState(true);
                                }} />
                            </span>
                        </SimpleItem>
                        <SimpleItem colSpan={2} label={{ text: '科目编号' }}>
                            <TextBox
                                disabled={diaParams.current?.args.isEdit}
                                value={KMBHAdd}
                                className="TextBox_Style"
                                // valueChangeEvent='keyup'
                                onChange={(e: any) => {
                                    const { event } = e;
                                    setKMBHAdd(event.target.value);
                                    const PKMBH1 = PKMBH.replace(/~\|/g, '');
                                    const value1 = event.target.value.slice(PKMBH1.length);
                                    const value2 = `${PKMBH}${value1}${"~|"}`;
                                    setKMBH(value2);
                                    setKMBHValue(event.target.value);
                                }} />
                        </SimpleItem>
                        <SimpleItem colSpan={2} label={{ text: '科目名称' }}  >
                            {/* <TextBox value={SubjectNumber} onFocusOut={onchanges}  /> */}
                            {/* onChange={onchanges} */}
                            <PTextBox defaultValue={PTextBoxValue.current}
                                changeData={(data: any) => {
                                    PTextBoxValue.current = data;
                                }} />
                        </SimpleItem>
                        <SimpleItem colSpan={2} label={{ text: '科目方向' }}  >
                            <SelectBox dataSource={items} value={SelectName ? SelectName : items[0].name} displayExpr='name' valueExpr='name' onSelectionChanged={onSelectionChangedDirection} />
                        </SimpleItem>
                        <SimpleItem colSpan={2} label={{ text: '科目类型' }} >
                            <SelectBox
                                dataSource={diaParams.current?.args.data}
                                value={SelectType}
                                // defaultValue="资产"
                                displayExpr='type' valueExpr='type'
                                onSelectionChanged={onSelectionChangedType}
                            />
                        </SimpleItem>
                        <SimpleItem colSpan={2}  >
                            <div style={{ width: '100%', borderBottom: "1px solid rgb(0,0,0,0.10)", height: "10px" }} />
                        </SimpleItem>
                        <SimpleItem colSpan={2} label={{ text: '对应报表项目' }} >
                            <TextBox
                                value={selectedYears}
                                readOnly={true}
                                className="TextBox_Style"
                                valueChangeEvent='keyup'
                                disabled
                                placeholder={
                                    intl('audit.yearly.select', '请选择.....')
                                }
                            />
                            <span style={{ position: 'absolute', right: '6px', top: "6px" }}>
                                <CpasIcon type="icon-xinzengkemu" onClick={() => {
                                    statementProjectRef.current.show({
                                        title: "选择报表项目",
                                        dbname: dbname,
                                        Data_ID: AccountDataID,
                                        ownerReport: '',
                                        selectMode: '1',
                                        // 选择 模式 0：单选 1：多选连机选择
                                        okCallback: (r: any) => {
                                            console.log(r, '@@@');

                                            const res = r.map((item: any) => {
                                                return item.itemName
                                            }).join();
                                            setSelectedYears(res);
                                        },
                                    });
                                }} />
                                <CpasIcon type="icon-close1" onClick={() => {
                                    setSelectedYears('')
                                }} />
                            </span>
                        </SimpleItem>
                    </Form>
                    <div style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: 'end', marginTop: "10px" }}>
                        <span style={{ fontSize: '12px', color: "#666" }}>一级或备抵科目需指定对应报表项目</span>
                    </div>
                    <div style={{ width: "100%", height: "14px", borderBottom: "1px solid rgb(0,0,0,0.10)" }} />
                    {!diaParams.current?.args.isEdit && <div className='isAddMoreYear'>
                        <span style={{ marginLeft: '8px', marginRight: '10px', whiteSpace: 'nowrap' }}>是否增加多年度:</span><CheckBox value={checkBoxState}
                            onValueChange={(e: any) => {
                                changeCheck(e);
                            }} />
                    </div>}

                </div>
            </Popup>
            <SubjectPopups ref={SubjectRef} wrapperAttr={{
                class: "fix-popup-title-width"
            }} />
            <ReportPopup ref={statementProjectRef} wrapperAttr={{
                class: "fix-popup-title-width"
            }} />
            <PopupComponents ref={PopupComponentsRef} wrapperAttr={{
                class: "fix-popup-title-width"
            }} />
        </>
    );
});


export default SubjectPopupData;